package com.tcs.channelHandler;

import com.tcs.model.ipdata.IpDataBean;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerChannelHeadler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(ServerChannelHeadler.class);

    public ServerChannelHeadler() {
        super();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("channel注册到一个EventLoop。");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("channel已创建但未注册到一个EventLoop。");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channel变为活跃状态（连接到了远程主机），现在可以接收和发送数据了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channel处于非活跃状态，没有连接到远程主机");
    }

    @Override
    protected void ensureNotSharable() {
        super.ensureNotSharable();
    }

    @Override
    public boolean isSharable() {
        return super.isSharable();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        logger.info("添加 handlerADDed");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        logger.info("删除 handlerADDed");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        logger.info(" log: {} " , ((ByteBuf) msg).toString());
//        ctx.channel().writeAndFlush("servers Request OK!");
        IpDataBean ipDataBean = (IpDataBean)msg;
        logger.info("msg:{} \n ipDataBean: {} " , msg.toString() , ipDataBean);
        ipDataBean.setPort(6666);
        ctx.writeAndFlush(ipDataBean);
        ReferenceCountUtil.release(msg);
    }

//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        logger.info("最后一次读取  ");
//        ctx.channel().writeAndFlush("最后一次读取!");
//    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("" , cause);
    }
}
